package com.pet_service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pet_service.entity.OrderHomeService;
import com.pet_service.entity.Orders;
import com.pet_service.entity.PetInfo;
import com.pet_service.entity.UserAddress;
import com.pet_service.entity.HomeServiceType;
import com.pet_service.enums.TOrderHomeServiceStatus;
import com.pet_service.enums.TOrderServiceType;
import com.pet_service.enums.TOrderStatus;
import com.pet_service.mapper.OrderHomeServiceMapper;
import com.pet_service.mapper.OrdersMapper;
import com.pet_service.mapper.PetInfoMapper;
import com.pet_service.mapper.UserAddressMapper;
import com.pet_service.mapper.HomeServiceTypeMapper;
import com.pet_service.service.BookingService;
import com.pet_service.util.EnumUtils;
import com.pet_service.vo.BookingRequestDTO;
import com.pet_service.vo.BookingResponseVO;
import com.pet_service.vo.PageBean;
import com.pet_service.vo.PageResultVO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 邹全伸
 * @version 1.0
 * @date 2025-10-03 15:20
 */
@Service
@Transactional
public class BookingServiceImpl implements BookingService {

    @Resource
    private OrdersMapper ordersMapper;

    @Resource
    private OrderHomeServiceMapper orderHomeServiceMapper;

    @Resource
    private PetInfoMapper petInfoMapper;

    @Resource
    private UserAddressMapper userAddressMapper;

    @Resource
    private HomeServiceTypeMapper homeServiceTypeMapper;

    @Override
    public PageResultVO<BookingResponseVO> listBookings(PageBean pageBean, Integer serviceType) {
        Page<Orders> page = new Page<>(pageBean.getPageNum(), pageBean.getPageSize());
        QueryWrapper<Orders> wrapper = new QueryWrapper<>();

        // 根据服务类型筛选（使用枚举实例匹配，修复类型不匹配问题）
        if (serviceType != null) {
            // 将int类型的serviceType转换为对应的枚举实例
            TOrderServiceType serviceTypeEnum = EnumUtils.getEnumByCode(TOrderServiceType.class, serviceType);
            if (serviceTypeEnum != null) {
                wrapper.eq("service_type", serviceTypeEnum);
            }
        } else {
            // 无筛选时查询上门服务和寄养服务
            wrapper.in("service_type",
                    TOrderServiceType.HOME_SERVICE,
                    TOrderServiceType.FOSTER_SERVICE);
        }
        wrapper.orderByDesc("created_at");

        IPage<Orders> orderPage = ordersMapper.selectPage(page, wrapper);
        List<Orders> orders = orderPage.getRecords();

        List<BookingResponseVO> result = new ArrayList<>();
        for (Orders order : orders) {
            // 获取宠物名称
            PetInfo pet = petInfoMapper.selectById(order.getPet_id());
            String petName = pet != null ? pet.getPet_name() : "未知";

            // 根据服务类型区分逻辑（直接比较枚举实例）
            String serviceName = "";
            String serviceTime = "";
            String fullAddress = "";
            TOrderHomeServiceStatus serviceStatus = null;

            // 上门服务判断（枚举实例直接比较）
            if (TOrderServiceType.HOME_SERVICE.equals(order.getService_type())) {
                QueryWrapper<OrderHomeService> homeServiceWrapper = new QueryWrapper<>();
                homeServiceWrapper.eq("order_id", order.getId());
                OrderHomeService homeService = orderHomeServiceMapper.selectOne(homeServiceWrapper);

                if (homeService != null) {
                    // 关联查询“上门服务类型名称”
                    HomeServiceType serviceTypeEntity = homeServiceTypeMapper.selectById(homeService.getService_type_id());
                    serviceName = serviceTypeEntity != null
                            ? serviceTypeEntity.getService_name()
                            : "未知服务类型";

                    // 格式化服务时间
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    serviceTime = sdf.format(homeService.getService_time());
                    serviceStatus = homeService.getService_status();

                    // 拼接服务地址
                    if (homeService.getService_address_id() != null) {
                        UserAddress address = userAddressMapper.selectById(homeService.getService_address_id());
                        if (address != null) {
                            fullAddress = String.format("%s%s%s%s",
                                    address.getProvince(), address.getCity(),
                                    address.getDistrict(), address.getDetail());
                        }
                    }
                }
            }
            // 寄养服务判断（枚举实例直接比较）
            else if (TOrderServiceType.FOSTER_SERVICE.equals(order.getService_type())) {
                serviceName = "寄养服务";
                // 格式化服务时间（使用订单创建时间）
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                serviceTime = sdf.format(order.getCreated_at());

                // 寄养状态与订单状态联动
                if (TOrderStatus.PAID.equals(order.getOrder_status())) {
                    serviceStatus = TOrderHomeServiceStatus.PENDING;
                } else if (TOrderStatus.SERVICING.equals(order.getOrder_status())) {
                    serviceStatus = TOrderHomeServiceStatus.EXECUTING;
                } else if (TOrderStatus.COMPLETED.equals(order.getOrder_status())) {
                    serviceStatus = TOrderHomeServiceStatus.COMPLETED;
                }
            }

            // 封装VO返回
            BookingResponseVO vo = new BookingResponseVO();
            vo.setId(order.getId());
            vo.setOrder_no(order.getOrder_no());
            vo.setPet_name(petName);
            vo.setService_name(serviceName); // 上门服务显示具体类型，寄养显示"寄养服务"
            vo.setService_time(serviceTime);
            vo.setFull_address(fullAddress);
            vo.setService_status(serviceStatus);

            result.add(vo);
        }

        return new PageResultVO<>(orderPage.getTotal(), result, pageBean);
    }
}
